<?php
if (!defined('__COLA_DIR__')) exit;
/**
 * 用户基类
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Widget_Abstract_Users extends Widget
{
    /**
     * 判断用户名称是否存在
     *
     * @access public
     * @param string $name 用户名称
     * @return boolean
     */
    public function nameExists($name)
    {
        $select = $this->db->select('uid')
		    ->from('table.users')
            ->where('name = ?', $name)
            ->limit(1)
			->fetchRow();
			
        if ($select && $this->request->uid == $select['uid']) {
			$select = false;
        }
        return $select ? false : true;
    }

    /**
     * 判断电子邮件是否存在
     *
     * @access public
     * @param string $mail 电子邮件
     * @return boolean
     */
    public function mailExists($mail)
    {
        $select = $this->db->select('uid')
		    ->from('table.users')
            ->where('mail = ?', $mail)
            ->limit(1)
			->fetchRow();
			
        if ($select && $this->request->uid == $select['uid']) {
			$select = false;
        }
        return $select ? false : true;
    }

    /**
     * 判断用户昵称是否存在
     *
     * @access public
     * @param string $nickName 昵称
     * @return boolean
     */
    public function nickNameExists($nickName)
    {
        $select = $this->db->select('uid')
		    ->from('table.users')
            ->where('nickName = ?', $nickName)
            ->limit(1)
			->fetchRow();
			
        if ($select && $this->request->uid == $select['uid']) {
			$select = false;
        }
        return $select ? false : true;
    }

    /**
     * 获取页面偏移
     *
     * @access protected
     * @param string $column 字段名
     * @param integer $offset 偏移值
     * @param string $group 用户组
     * @param integer $pageSize 分页值
     * @return integer
     */
    protected function getPageOffset($column, $offset, $group = NULL, $pageSize = 20)
    {
        $select = $this->db->select(array('COUNT(table.users.uid)' => 'num'))
		    ->from('table.users')
            ->where("table.users.{$column} > {$offset}");

        if (!empty($group)) {
            $select->where('table.users.group = ?', $group);
        }
		
		$count = $select->fetchObject()->num + 1;
        return ceil($count / $pageSize);
    }

    /**
     * 通用过滤器
     *
     * @access public
     * @param array $value 需要过滤的行数据
     * @return array
     */
    public function filter(array $value)
    {
		if (isset($value['uid'], $value['name'])) {	
            //生成静态链接
            $routeExists = (NULL != Router::get('author'));

            $value['permalink'] = $routeExists ? Router::url('author', $value, $this->options->index) : '#';
		}

		/** 插件接口 */
		//HOOK $value | PLUG_Abstract_Users_Filter($value, $this);
		
        return $value;
    }

    /**
     * 将每行的值压入堆栈
     *
     * @access public
     * @param array $value 每行的值
     * @return array
     */
    public function push(array $value)
    {
        $value = $this->filter($value);
        return parent::push($value);
    }

    /**
     * 查询方法
     *
     * @access public
     * @return Db_Query
     */
    public function select()
    {
        return $this->db->select()
		    ->from('table.users');
    }

    /**
     * 增加用户
     *
     * @access public
     * @param array $values 用户结构数组
     * @return integer
     */
    public function insert(array $values)
    {
        /** 构建插入结构 */
        $user = array(
            'group'         =>  empty($values['group']) ? 'visitor' : $values['group'],
			'name'          =>  empty($values['name']) ? '' : htmlspecialchars($values['name']),
			'nickName'      =>  empty($values['nickName']) ? '' : htmlspecialchars($values['nickName']),
            'password'      =>  empty($values['password']) ? '' : $values['password'],
            'salt'          =>  empty($values['salt']) ? sha1(Common::randString(20)) : $values['salt'],
            'mail'          =>  empty($values['mail']) ? '' : $values['mail'],
            'mobile'        =>  empty($values['mobile']) ? '' : $values['mobile'],
            'url'           =>  empty($values['url']) ? '' : $values['url'],
            'sign'          =>  empty($values['sign']) ? '' : $values['sign'],
            'intro'         =>  empty($values['intro']) ? '' : $values['intro'],
            'contentsNum'   =>  empty($values['contentsNum']) ? 0 : intval($values['contentsNum']),
            'commentsNum'   =>  empty($values['commentsNum']) ? 0 : intval($values['commentsNum']),
            'scores'        =>  empty($values['scores']) ? 0 : intval($values['scores']),
            'ip'            =>  empty($values['ip']) ? $this->request->longIp() : $values['ip'],
            'pic'           =>  empty($values['pic']) ? '' : $values['pic'],
            'created'       =>  empty($values['created']) ? $this->options->time : $values['created'],
            'logged'        =>  empty($values['logged']) ? 0 : intval($values['logged']),
            'activated'     =>  empty($values['activated']) ? 0 : intval($values['activated']),
        );

        if (!empty($values['uid'])) {
            $user['uid'] = $values['uid'];
        }
		
		/** 保证密码不为空 */
        if (empty($values['password'])) {
            $user['password'] = substr(uniqid(), 7);
        }
		$user['password'] = Common::passwordHash($user['password']);
		
		/** 插件接口 */
		//HOOK $user | PLUG_Abstract_Users_Insert($values, $this);

        return $this->db->insert('table.users')
		    ->values($user)
			->lastInsertId();
    }

    /**
     * 更新用户
     *
     * @access public
     * @param int $uid 用户uid
     * @param array $values 用户结构数组
     * @return integer
     */
    public function update($uid, array $values)
    {
        /** 构建插入结构 */
        $update = array(
            'group'         =>  empty($values['group']) ? 'visitor' : $values['group'],
			'name'          =>  empty($values['name']) ? '' : htmlspecialchars($values['name']),
			'nickName'      =>  empty($values['nickName']) ? '' : htmlspecialchars($values['nickName']),
            'salt'          =>  empty($values['salt']) ? sha1(Common::randString(20)) : $values['salt'],
            'mail'          =>  empty($values['mail']) ? '' : $values['mail'],
            'mobile'        =>  empty($values['mobile']) ? '' : $values['mobile'],
            'url'           =>  empty($values['url']) ? '' : $values['url'],
            'sign'          =>  empty($values['sign']) ? '' : $values['sign'],
            'intro'         =>  empty($values['intro']) ? '' : $values['intro'],
            'contentsNum'   =>  empty($values['contentsNum']) ? 0 : intval($values['contentsNum']),
            'commentsNum'   =>  empty($values['commentsNum']) ? 0 : intval($values['commentsNum']),
            'scores'        =>  empty($values['scores']) ? 0 : intval($values['scores']),
            'ip'            =>  empty($values['ip']) ? $this->request->longIp() : $values['ip'],
            'pic'           =>  empty($values['pic']) ? '' : $values['pic'],
            'logged'        =>  empty($values['logged']) ? 0 : intval($values['logged']),
            'activated'     =>  empty($values['activated']) ? 0 : intval($values['activated']),
        );

        $user = array();
        foreach ($values as $key => $val) {
            if (array_key_exists($key, $update)) {
                $user[$key] = $update[$key];
            }
        }
		
        /** 更新创建时间 */
        if (!empty($values['created'])) {
            $user['created'] = $values['created'];
        }
		
		/** 保证密码不为空 */
        if (!empty($values['password'])) {
		    $user['password'] = Common::passwordHash($values['password']);
        } else {
			unset($user['password']);
		}

		/** 插件接口 */
		//HOOK $user | PLUG_Abstract_Users_Update($values, $this);
		
        return $this->db->update('table.users')
		    ->where('uid = ?', $uid)
			->values($user)
			->affectedRows();
    }

    /**
     * 删除用户
     *
     * @access public
     * @param int $uid 用户uid
     * @return integer
     */
    public function delete($uid)
    {
		/** 插件接口 */
		//HOOK PLUG_Abstract_Users_Delete($uid, $this);
		
        return $this->db->delete('table.users')
		    ->where('uid = ?', $uid)
			->affectedRows();
    }

    /**
     * 输出用户头像
     *
     * @access public
     * @return void
     */
    public function ___avatar()
    {
		$icon = $this->pic;
		if($icon){
		    strpos($icon, '://') === FALSE && $icon = $this->options->uploadUrl . $icon;
		}else{
			$icon = $this->options->staticUrl('images/avatar-default.png', false);
		}
        return $icon;
    }
}
